package com.wesley.framework.protocol.dubbo;

import com.wesley.framework.Invocation;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * NettyClientHandler
 *
 * @author WangPanYong
 * @since 2021/11/17 14:12
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private Invocation invocation;
    private ChannelHandlerContext context;

    /**
     * RPC调用的返回结果
     */
    private String result;

    @Override
    public synchronized Object call() throws Exception {
        // 参数信息发送服务端
        ByteBuf buf = Unpooled.copiedBuffer(ProtostuffUtil.serializer(this.invocation));
        context.writeAndFlush(buf);
        // 等待服务端返回调用结果
        wait();
        return result;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" 客户端连接成功 ");
        this.context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(" 客户端接收结果");

        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        result = ProtostuffUtil.deserializer(bytes, String.class);
        // 唤醒等待线程
        notify();
    }

    public void setInvocation(Invocation invocation) {
        this.invocation = invocation;
    }

    public String getResult() {
        return result;
    }
}
